<template>
  <div class="admin" v-loading="loading2" element-loading-text="上传中，请稍后..." element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)">
    <div class="w">
      <div class="container" ref="container">
        <div class="top clearfix">
          <el-breadcrumb separator-class="el-icon-arrow-right" class="fl">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>管理员工</el-breadcrumb-item>
          </el-breadcrumb>
          <div class="btns fr">
            <el-button v-if="isAdmin && (authorizeCode==101 || authorizeCode==201)" plain class="bmks" type="info" @click="$router.push({name: 'bmks'})">管理部门</el-button>
            <el-button v-if="isAdmin" class="seat" type="warning" @click="$router.push({name: 'seat'})">管理座位</el-button>
            <el-button v-if="isLogin && Authcode!=101" class="personal" type="info" @click="$router.push({name: 'personal'})">个人信息</el-button>
            <el-button v-if="isLogin" type="danger" class="loginOut" @click="outLogin">退出</el-button>
          </div>
        </div>

        <!-- 顶部搜索 -->
        <el-col :span="24" class="header-op" style="height: 62px;">
          <el-form :inline="true">
            <el-form-item v-if="lockD">
              <!-- <el-cascader v-model="params.department" :options="options.department" placeholder="部门 / 科室"></el-cascader> -->
              <el-select v-model="condition.bm" placeholder="部门" @change="changeDepartment" @clear="clearD" style="max-width=200px">
                <el-option v-for="(item,index) in options.department" :key="index" :label="item.value" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item v-if="lockS">
              <el-select v-model="condition.ks" placeholder="科室" @clear="goSearch">
                <el-option v-for="(item,index) in options.section" :key="index" :label="item.secname" :value="item.secname">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-input placeholder="搜索" v-model="condition.searchText" clearable @keyup.enter.native="goSearch" @clear="goSearch">
                <i slot="prefix" class="el-input__icon el-icon-search"></i>
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="goSearch" icon="el-icon-search"></el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" plain @click="addWorker">新增</el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="batchOperation">批量操作</el-button>
            </el-form-item>
            <!-- <el-form-item>
            <el-button type="danger" plain>批量冻结</el-button>
          </el-form-item> -->
            <!-- <el-form-item>
            <el-button type="success" plain>批量解冻</el-button>
          </el-form-item> -->
            <el-form-item v-if="Authcode == 101">
              <el-upload  class="upload"  ref="upload"  action="/api/updatedb/" :headers="{'Token': Token}"  :limit="1" :show-file-list="false"  :before-upload="beforeUpload" :on-success="onSuccess" :on-error="onError">
                 <el-button slot="trigger" plain type="success">上传excel</el-button>
              </el-upload>
            </el-form-item>
            <el-form-item>
               <el-button type="success" @click="download">下载excel</el-button>
            </el-form-item>

          </el-form>
        </el-col>

        <!-- 表格内容 -->
        <el-table v-loading="loading" stripe :max-height="tableHeight" :data="initData.list" :header-cell-style="{'background-color': '#e8ecf1','color': '#0d2d84'}" :row-style="{'padding': '0px'}" :cell-style="{'padding': '5px'}" @selection-change="handleSelectionChange">

          <el-table-column align="center" type="selection" width="55" :selectable="checkboxSelect"></el-table-column>

          <el-table-column align="center" header-align='center' label="姓名" prop="name" width="100"></el-table-column>
          <el-table-column align="center" header-align='center' label="部门" prop="department" width="150"></el-table-column>
          <el-table-column align="center" header-align='center' label="科室" prop="section" width="150">
          </el-table-column>
          <el-table-column align="center" header-align='center' label="职务" prop="position" width="160">
          </el-table-column>
          <el-table-column align="center" header-align='center' label="房间号" width="90">
            <template slot-scope="scope">
              {{scope.row.seatinfo.roomnumber}}
            </template>
          </el-table-column>
          <el-table-column align="center" header-align='center' label="卡位编号" width="100">
            <template slot-scope="scope">
              {{scope.row.seatinfo.seatid}}
            </template>
          </el-table-column>
          <el-table-column align="center" header-align='center' label="手机" width="120" prop="mobile">
          </el-table-column>
          <el-table-column align="center" header-align='center' label="内线" width="100">
            <template slot-scope="scope">
              {{scope.row.seatinfo.phonenumber}}
            </template>
          </el-table-column>
          <el-table-column align="center" header-align='center' label="IP地址" width="150">
            <template slot-scope="scope">
              {{scope.row.seatinfo.ipaddress}}
            </template>
          </el-table-column>

          <el-table-column align="center" header-align='center' label="管理权限" width="100" prop="authcode">
            <template slot-scope="scope">
              {{((key)=>{
                switch(key){
                  case 101:return '超级管理员';break;
                  case 201:return '部门管理员';break;
                  case 301:return '科室管理员';break;
                  default:return '';break;
                }
              })(scope.row.authcode)}}
            </template>
          </el-table-column>

          <el-table-column align="center" header-align='center' label="邮箱" width="120" prop="email">
            <template slot-scope="scope">
              {{scope.row.email == '暂无' ? '' : scope.row.email}}
            </template>
          </el-table-column>

          <el-table-column label="操作" align="center" width="140" fixed="right">
            <template slot-scope="scope">
              <div class="buttons">
                <!-- <el-button @click="showDetail(scope.row)" type="primary" size="mini" icon="el-icon-view"></el-button> -->
                <el-button @click="changeData(scope.row)" size="mini" icon="el-icon-edit" :disabled="(scope.row.authcode <= Authcode)&&(scope.row.mobile != Username)"></el-button>
                <el-button @click="deleteData(scope.row)" type="danger" size="mini" icon="el-icon-delete" :disabled="scope.row.authcode <= Authcode"></el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination v-show="this.initData.total > 0" @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-size="params.pageSize" :current-page="params.page" :page-sizes="pageSizes" layout="total, sizes, prev, pager, next, jumper" :total="initData.total">
        </el-pagination>

        <!-- 新增/编辑人员 -->
        <el-dialog :visible.sync="dialog.edit" width="70%">
          <template slot="title">
            <div class="title">{{((key)=>{
            switch(key){
              case 0: return '新增职员';break;
              case 1: return '编辑职员';break;
            }
            })(editData.mode)}}</div>
          </template>
          <el-form :inline="true" :model="editData" label-width="200px" ref="editData" :rules="rules">

            <el-form-item label="姓名：" prop="name">
              <el-input style="width: 200px" v-model="editData.name"></el-input>
            </el-form-item>
            <el-form-item label="手机：" prop="mobile">
              <el-input style="width: 200px" v-model="editData.mobile"></el-input>
            </el-form-item>
            <el-form-item label="部门：" prop="department_id">
              <el-select style="width: 200px" v-model="editData.department_id" placeholder="部门" @change="changeDepartment2">
                <el-option v-for="(item, index) in options.department" :key="index" :label="item.value" :value="item.id" v-show="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="科室：" prop="section_id">
              <el-select style="width: 200px" v-model="editData.section_id" placeholder="科室">
                <el-option v-for="(item,index) in options.section2" :key="index" :label="item.secname" :value="item.section_id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="职务：" prop="position">
              <el-input style="width: 200px" v-model="editData.position"></el-input>
              <!-- <el-tooltip class="item" effect="dark" content="如有多个职位则用顿号(、)隔开" placement="right">
              <i class="el-icon-warning-outline" style="font-size: 20px"></i>
            </el-tooltip> -->
            </el-form-item>
            <el-form-item label="邮箱：" prop="email">
              <el-input style="width: 200px" v-model="editData.email"></el-input>
            </el-form-item>
            <!-- <el-form-item label="房间号：" prop="seatinfo.roomnumber" v-show="editData.mode == 1">
              <el-input style="width: 200px" v-model="editData.seatinfo.roomnumber" :disabled="true"></el-input>
            </el-form-item> -->
            <el-form-item label="卡位编号：" prop="seatinfo.seatid">
              <!-- <el-input style="width: 200px" v-model="editData.seatinfo.seatid"></el-input> -->
              <el-autocomplete style="width: 200px" v-model="editData.seatinfo.seatid" :fetch-suggestions="querySearch" :trigger-on-focus="false" @select="handleSelect"></el-autocomplete>
            </el-form-item>
            <!-- <el-form-item label="内线：" prop="seatinfo.phonenumber" v-show="editData.mode == 1">
              <el-input style="width: 200px" v-model="editData.seatinfo.phonenumber" :disabled="true"></el-input>
            </el-form-item> -->
            <!-- <el-form-item label="IP地址：" prop="seatinfo.ipaddress" v-show="editData.mode == 1">
              <el-input style="width: 200px" v-model="editData.seatinfo.ipaddress" :disabled="true"></el-input>
            </el-form-item> -->
            <el-form-item label="管理权限：" prop="authcode">
              <el-select style="width: 200px" v-model="editData.authcode" @change="openSelect" :disabled="editData.mobile == Username || Authcode >= editData.authcode">
                <el-option v-for="item in options.authcode" :key="item.value" :label="item.label" :value="item.value" :disabled="item.value <= Authcode">
                </el-option>
              </el-select>
              <el-link v-show="editData.auth_list.length > 0 && editData.authcode > Authcode" @click="openSelect2">(...)</el-link>
            </el-form-item>

            <el-form-item label="密码：" v-if="Authcode == 101 && editData.mode == 1">
              <el-button type="warning" plain @click="changePw">修改密码</el-button>
            </el-form-item>

            <div class="btns">
              <el-button type="primary" plain @click="submitData('editData')">提交</el-button>
              <el-button plain @click="dialog.edit = false">取消</el-button>
            </div>

          </el-form>
        </el-dialog>

        <!-- 选择管理部门或科室 -->
        <el-dialog :visible.sync="dialog.select" width="30%" class="dialog-select" :show-close="false">
          <template slot="title">
            <div class="title">{{((key)=>{
            switch(key){
              case 201: return '选择管理的部门';break;
              case 301: return '选择管理的科室';break;
            }
            })(editData.authcode)}}</div>
          </template>
          <div class="total">{{selection.length}}/{{((key)=>{
            switch(key){
              case 201: return options.department.length;break;
              case 301: return options.section2.length;break;
            }
            })(editData.authcode)}}</div>
          <div class="selection">
            <ul v-if="editData.authcode == 201">
              <li v-for="(item,index) in options.department" :key="index" @click="selectDmks(item.id)">
                <i class="icon-span" :class="Selected(item.id) ? 'icon-span-select' : ''"></i>
                {{item.value}}
              </li>
            </ul>
            <ul v-if="editData.authcode == 301">
              <li v-for="(item,index) in options.section2" :key="index" @click="selectDmks(item.section_id)">
                <i class="icon-span" :class="Selected(item.section_id) ? 'icon-span-select' : ''"></i>
                {{item.secname}}
              </li>
            </ul>
          </div>
          <div class="btns">
            <el-button type="primary" @click="saveSelection">保存</el-button>
            <el-button plain @click="cancelSelection">取消</el-button>
          </div>
        </el-dialog>

        <!-- 修改密码 -->
        <el-dialog :visible.sync="dialog.pw" width="30%">
          <template slot="title">
            <div class="title">修改密码</div>
          </template>
          <el-form ref="pw_form" :model="pw_form" label-width="80px" :rules="rules2">
            <el-form-item label="新密码" prop="n_pw">
              <el-input v-model="pw_form.n_pw" placeholder="密码为空则重置密码" onpaste="return false" ondragenter="return false" oncontextmenu="return false;" style="ime-mode:disabled" onkeyup="this.value=this.value.replace(/[\u4e00-\u9fa5]/gi,'')" show-password></el-input>
            </el-form-item>
            <div class="pw-btn" style="text-align: center;">
              <el-button @click="dialog.pw = false">取 消</el-button>
              <el-button type="primary" @click="changePw2('pw_form')">确 定</el-button>
            </div>
          </el-form>
        </el-dialog>

        <!-- 批量操作 -->
        <el-dialog :visible.sync="dialog.batch" width="300px">
          <div style="text-align: center;">
            <el-button type="danger" plain @click="delSelections">批量删除</el-button>
            <el-button @click="changeKeshi">转移科室</el-button>
          </div>
        </el-dialog>

        <!-- 转移科室 -->
        <el-dialog :visible.sync="dialog.changeKs" width="615px">
          <el-form :inline="true" :model="editData" label-width="75px" ref="editData" :rules="rules">
            <el-form-item label="部门：" prop="department_id">
              <el-select style="width: 200px" v-model="editData.department_id" placeholder="部门" @change="changeDepartment3">
                <el-option v-for="(item, index) in options.department2" :key="index" :label="item.value" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="科室：" prop="section_id">
              <el-select style="width: 200px" v-model="editData.section_id" placeholder="科室">
                <el-option v-for="(item,index) in options.section2" :key="index" :label="item.secname" :value="item.section_id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <div style="display: flex;">
            <el-button style="width:200px;flex:1;" type="primary" @click="changeKeshi">确定</el-button>
            <el-button style="width:200px;flex:1;" @click="dialog.changeKs = false">取消</el-button>
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "admin",
  data() {
    return {
      tableHeight: 0,
      isLogin: false,
      isAdmin: false,
      loading2: false,// 上传文件等待
      loading: false,
      lockD: true,
      lockS: true,
      pageSizes: [5, 10, 15, 20, 50, 100],
      initData: {
        list: [],
        // current: 1,
        total: 0
      },
      params: {
        page: 1,
        pageSize: 10,
        searchText: "",
        department: '',
        section: '',
      },
      options: {
        department: [],
        department2: [],
        section: [],
        section2: [],
        authcode: [
          {
            label: "超级管理员",
            value: 101
          },
          {
            label: "部门管理员",
            value: 201
          },
          {
            label: "科室管理员",
            value: 301
          },
          {
            label: "无",
            value: 401
          }
        ]
      },
      condition: {
        bm: '所有',
        ks: '',
        searchText: '',
      },
      dialog: {
        edit: false,
        select: false,
        pw: false,
        batch: false,
        changeKs: false,
      },
      multipleSelection: [],
      editData: {
        mode: 0, // 0==>添加  1==>修改
        name: "",
        department: "",
        department_id: "",
        email: "",
        // section: '',
        section_id: '',
        position: "",
        mobile: '',
        authcode: 401,
        authcode: 401,// 备份权限
        auth_list: [],
        seatinfo: {
          id: "",
          ipaddress: '',
          phonenumber: '',
          roomnumber: '',
          roomname: '暂无',
          seatid: '',
          seatid2: '',
        }
      },
      rules: {
        name: [{ validator: this.validName, trigger: "blur" }],
        department_id: [{ validator: this.validDepartment, trigger: "blur" }],
        section_id: [{ validator: this.validSectionId, trigger: "blur" }],
        position: [{ validator: this.validPosition, trigger: "blur" }],
        mobile: [{ validator: this.validMobile, trigger: "blur" }],
        email: [{ validator: this.validEmail, trigger: "blur" }],
        'seatinfo.roomnumber': [{ validator: this.validRoomnumber, trigger: "blur" }],
        'seatinfo.seatid': [{ validator: this.validSeatid, trigger: "blur" }],
        'seatinfo.phonenumber': [{ validator: this.validPhonenumber, trigger: "blur" }],
        'seatinfo.ipaddress': [{ validator: this.validIpaddress, trigger: "blur" }]
      },
      pw_form: {
        n_pw: '',
      },
      rules2: {
        n_pw: [{ validator: this.validN_pw, trigger: "blur" }],
      },
      selection: [],
      seat_list: [],
    };
  },
  created() {
    this.getUserInfo();
    this.initList();// 管理部门初始化
    // this.getDpsinfo();
    this.search();
    // this.init();// 所有部门
  },
  mounted() {
    this.$nextTick(() => {
      this.tableHeight = this.$refs.container.offsetHeight - 205;
      // console.log(this.$refs.container.offsetHeight)
      // console.log(this.tableHeight)
    })
  },
  computed: {
    Authcode() {
      return this.$cookies.get("__ac")
    },
    Token() {
      return this.$cookies.get("__tk")
    },
    Username() {
      return this.$cookies.get('__un')
    }
  },
  methods: {
    init() {
      if (this.options.department2.length) {
        return
      }
      this.axios({
        method: 'GET',
        url: '/api/dpsinfo/',
        headers: {
          'Token': this.$cookies.get('__tk')
        },
        // data: this.$qs.stringify()
        params: {
          username: '18888888888'
        }
      }).then(res => {
        // console.log('alldps res==>', res)
        if (res.data.code == 200) {
          let obj = res.data.data;
          for (let k in obj) {
            this.options.department2.push({
              value: obj[k].department_name,
              id: obj[k].department_id,
              chlidren: obj[k].section
            })
          }
          // console.log('dpsinfo==>', this.options.department)
        } else {
          this.$message.warning('请询问相关人员(获取所有部门失败)');
        }
      }).catch(error => {
        // console.log('error==>', error)
        this.loading = false;
        this.$message.error(error || "出现错误，请稍后再试")
      })
    },
    // 获取用户数据
    getUserInfo() {
      let tokenString = this.$cookies.get("__tk");
      this.authorizeCode = this.$cookies.get("__ac");
      if (!tokenString) {
        this.isLogin = false;
        this.$router.push('/home')
      } else {
        this.isLogin = true;
      }
      if (this.authorizeCode == 101 || this.authorizeCode == 301 || this.authorizeCode == 201) {
        this.isAdmin = true;
        if (this.authorizeCode == 301) {
          this.lockD = false;
          this.lockS = true;
        } else if (this.authorizeCode == 201) {
          this.lockD = true;
          this.lockS = true;
        }
      } else {
        this.isAdmin = false;
        this.$router.push('/home')
      }
      // console.log('登录状态==>', this.isLogin)
      // console.log('管理状态==>', this.isAdmin)

    },
    // 退出
    outLogin() {
      if (this.isLogin) {
        this.$cookies.keys().map((cookieName) => {
          this.$cookies.remove(cookieName);
        });
        this.isLogin = false;
        this.isAdmin = false;
        this.$message.success('退出成功');
        setTimeout(() => {
          this.$router.push({ name: 'home' });
        }, 500);
      } else {
        return
      }
    },
    // 初始化管理部门
    initList() {
      this.axios({
        method: 'GET',
        url: '/api/dpsinfo/',
        headers: {
          'Token': this.$cookies.get('__tk')
        },
        // data: this.$qs.stringify()
        params: {
          username: this.$cookies.get('__un')
        }
      }).then(res => {
        // console.log('dps res==>', res)
        if (res.data.code == 200) {
          if (this.$cookies.get('__ac') == 101 || this.$cookies.get('__ac') == 201) {
            this.options.department.push({
              value: '所有',
              id: 0,
              chlidren: []
            })
          }
          let obj = res.data.data;
          for (let k in obj) {
            this.options.department.push({
              value: obj[k].department_name,
              id: obj[k].department_id,
              chlidren: obj[k].section
            })
          }
          // console.log('dpsinfo==>', this.options.department)
        } else {
          this.$message.warning('请询问相关人员(获取部门失败)');
        }
      }).catch(error => {
        // console.log('error==>', error)
        this.loading = false;
        this.$message.error(error || "出现错误，请稍后再试")
      })
    },
    // 部门-科室联动
    changeDepartment() {
      this.condition.ks = '';
      for (const i in this.options.department) {
        if (this.options.department[i].value == this.condition.bm) {
          this.options.section = this.options.department[i].chlidren;
        }
      }
    },
    // 部门-科室联动 表单
    changeDepartment2() {
      this.editData.section_id = '';
      for (const i in this.options.department) {
        if (this.options.department[i].id == this.editData.department_id) {
          this.options.section2 = this.options.department[i].chlidren;
        }
      }
    },
    // 部门-科室联动 表单
    changeDepartment3(val) {
      this.editData.section_id = '';
      for (const i in this.options.department2) {
        if (this.options.department2[i].id == val) {
          this.options.section2 = this.options.department2[i].chlidren;
        }
      }
    },
    // 清空部门
    clearD() {
      this.condition.section = '';
      this.options.section = '';
      this.goSearch();
    },
    // 搜索请求
    search() {
      // console.log("发起搜索请求");
      if (this.loading) {
        return
      }
      this.loading = true;// 加载显示
      this.axios({
        method: 'POST',
        url: '/api/data_auth_search/',
        headers: {
          'Token': this.$cookies.get('__tk')
        },
        data: this.$qs.stringify({
          username: this.$cookies.get('__un'),
          authcode: this.$cookies.get('__ac'),
          page: this.params.page,
          perpageitem: this.params.pageSize,
          department: this.params.department,
          section: this.params.section,
          searchText: this.params.searchText,
        })
      }).then(res => {
        // console.log('search res==>', res)
        if (res.data.code == 100) {
          this.initData.list = res.data.data.personinfo;
          this.initData.total = res.data.data.pageinfo.totalnum;
        } else {
          this.$message.error(error || "出现错误，请稍后再试");
        }
        this.loading = false;
      }).catch(error => {
        this.loading = false;
        // console.log('error==>', error)
        this.$message.error(error || "出现错误，请稍后再试")
      })

    },
    // 改变搜索条件
    goSearch() {
      this.params.page = 1;
      this.params.department = this.condition.bm == '所有' ? '' : this.condition.bm;
      this.params.section = this.condition.ks;
      this.params.searchText = this.condition.searchText;
      this.search();
    },
    // 查询是否有管理部门科室
    checkBmks(name, authcode) {
      return new Promise((resolve, reject) => {
        let arr = [];
        if (authcode == 401 || authcode == 101) {
          resolve(arr)
        } else {
          this.axios({
            method: 'GET',
            url: '/api/dpsinfo/',
            headers: {
              'Token': this.$cookies.get('__tk')
            },
            params: {
              username: name
            }
          }).then(res => {
            // console.log('checkBmks res==>', res)
            if (res.data.code == 200 && res.data.data) {
              let obj = res.data.data;
              if (authcode == 201) {
                for (let k in obj) {
                  arr.push(obj[k].department_id)
                }
                resolve(arr)
              } else {
                for (let k in obj[0].section) {
                  arr.push(obj[0].section[k].section_id)
                }
                resolve(arr)
              }

            } else {
              this.$message.warning('请询问相关人员(获取管理的部门科室失败)');
              resolve(arr)
            }
          }).catch(error => {
            // console.log('error==>', error)
            this.loading = false;
            this.$message.error(error || "出现错误，请稍后再试")
            resolve(arr)
          })
        }
      })
    },
    // 编辑职工
    async changeData(o) {
      if (this.$refs.editData) {
        this.$refs.editData.resetFields();
      }
      let selection2 = await this.checkBmks(o.mobile, o.authcode);
      // console.log('selection2==>', selection2)
      this.editData = {
        mode: 1, // 0==>添加  1==>修改
        id: o.id,
        name: o.name,
        department: o.department,
        department_id: o.department_id,
        email: o.email == '暂无' ? '' : o.email,
        // section: o.section,
        section_id: o.section_id,
        position: o.position,
        mobile: o.mobile,
        authcode: o.authcode,
        authcode2: o.authcode,
        auth_list: selection2,
        seatinfo: {
          id: o.seatinfo.id,
          ipaddress: o.seatinfo.ipaddress,
          phonenumber: o.seatinfo.phonenumber,
          roomnumber: o.seatinfo.roomnumber,
          seatid: o.seatinfo.seatid,
          seatid2: o.seatinfo.seatid,
          roomname: o.seatinfo.roomname,
        }
      };
      // this.changeDepartment2();
      for (const i in this.options.department) {
        if (this.options.department[i].value == this.editData.department) {
          this.options.section2 = this.options.department[i].chlidren;
        }
      }
      this.loadAll();
      this.dialog.edit = true;
    },
    // 新增职工
    addWorker() {
      if (this.$refs.editData) {
        this.$refs.editData.resetFields();
      }
      this.editData = {
        mode: 0, // 0==>添加  1==>修改
        // id: "",
        name: '',
        department: '',
        department_id: '',
        email: '',
        // section: '',
        section_id: '',
        position: '',
        mobile: '',
        authcode: 401,
        authcode2: 401,
        auth_list: [],
        seatinfo: {
          id: '',
          ipaddress: '',
          phonenumber: '',
          roomnumber: '',
          roomname: '暂无',
          seatid: '',
          roomname: '',
        }
      };
      this.options.section2 = [];
      this.dialog.edit = true
    },
    // 新增/编辑提交
    submitData(formName) {
      // console.log('editdata==>', this.editData)
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.editData.mode == 0) {
            // 新增请求
            let data = {
              name: this.editData.name,
              // department: this.editData.department,
              email: this.editData.email,
              // section: this.editData.section,
              section_id: this.editData.section_id,
              position: this.editData.position,
              mobile: this.editData.mobile,
              seatinfo_id: this.editData.seatinfo.id,
              authcode: this.editData.authcode,
              department_list: this.editData.authcode == 201 ? JSON.stringify(this.editData.auth_list) : '[' + this.editData.department_id + ']',
              section_list: this.editData.authcode == 301 ? JSON.stringify(this.editData.auth_list) : '',
            }
            // console.log('add data==>', data)
            this.axios({
              method: 'put',
              url: '/api/update_delete_info/',
              headers: {
                'Token': this.$cookies.get('__tk')
              },
              data: data
            }).then(res => {
              // console.log('add res==>', res);
              this.$message.success("新增成功!");
              this.dialog.edit = false;
              this.changeDepartment(this.params);
              this.search();
            }).catch(error => {
              // console.log('error==>', error);
              this.$message.error(error || "出现错误，请稍后再试")
            })

          } else {
            this.changeAuthcode().then(val => {
              if (!val) {
                this.$message.error('修改权限失败');
                return;
              } else {
                // 编辑请求
                let data = {
                  id: this.editData.id,
                  name: this.editData.name,
                  // department: this.editData.department,
                  email: this.editData.email,
                  // section: this.editData.section,
                  section_id: this.editData.section_id,
                  position: this.editData.position,
                  mobile: this.editData.mobile,
                  authcode: this.editData.authcode,
                  seatinfo_id: this.editData.seatinfo.id,
                  // ipaddress: this.editData.seatinfo.ipaddress,
                  // phonenumber: this.editData.seatinfo.phonenumber,
                  // roomnumber: this.editData.seatinfo.roomnumber,
                  // roomname: this.editData.seatinfo.roomname,
                  // seatid: this.editData.seatinfo.seatid,
                }
                // console.log('编辑请求-------', data)
                this.axios({
                  method: 'post',
                  url: '/api/update_delete_info/',
                  headers: {
                    'Token': this.$cookies.get('__tk')
                  },
                  data: this.$qs.stringify(data)
                }).then(res => {
                  // console.log('edit res==>', res);
                  if (res.data.code == 200) {
                    this.$message.success("编辑成功!");
                    this.dialog.edit = false;
                    this.search();
                  } else if (res.data.code == 400) {
                    this.$message.error(res.data.msg)
                  }

                }).catch(error => {
                  // console.log('error==>', error);
                  this.$message.error(error || "出现错误，请稍后再试");
                })
              }
            })

          }

        } else {
          this.$message.warning("请检查信息是否有误!");
          return false;
        }
      });
    },
    // 修改权限
    changeAuthcode() {
      return new Promise((resolve, reject) => {
        let data = {
          mobile: this.editData.mobile,
          authcode: this.editData.authcode,
          department_list: this.editData.authcode == 201 ? JSON.stringify(this.editData.auth_list) : '[' + this.editData.department_id + ']',
          section_list: this.editData.authcode == 301 ? JSON.stringify(this.editData.auth_list) : '',
        }
        // console.log('authcode data==>', data)
        // console.log('修改权限请求-----------------')
        this.axios({
          method: 'post',
          url: '/api/authchange/',
          headers: {
            'Token': this.$cookies.get('__tk')
          },
          data: this.$qs.stringify(data)
        }).then(res => {
          // console.log('auth res==>', res)
          if (res.data.code != 200) {
            resolve(false)
            // this.$message.error(res.data.msg)
          }
          resolve(true)
        }).catch(error => {
          // console.log('error==>', error)
          resolve(false)
        });
      });

    },
    // 删除职工
    deleteData(o) {
      // console.log("删除id==>", o.mobile);
      this.$confirm(`该操作不可逆, 是否确认删除?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.axios({
          method: 'delete',
          url: '/api/update_delete_info/',
          headers: {
            'Token': this.$cookies.get('__tk')
          },
          data: { id: o.id }
        }).then(res => {
          // console.log('res==>', res)
          if (res.data.code == 100) {
            this.$message.success(res.data.msg)
            // this.params.page = 1;
            this.search();
          }
        }).catch(error => {
          // console.log('error==>', error)
          this.$message.error(error || "出现错误，请稍后再试")
        });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    // 禁用自己和同级或上级的多选
    checkboxSelect(row, rowIndex) {
      if (row.authcode <= this.$cookies.get('__ac')) {
        return false // 禁用
      } else {
        return true // 不禁用
      }
    },
    // 批量操作
    batchOperation() {
      // console.log("批量操作==>", this.multipleSelection);
      if (this.multipleSelection.length == 0) {
        return
      }
      this.dialog.batch = true;
      this.init();// 所有部门

    },
    // 批量删除
    delSelections() {
      // console.log("批量删除==>", this.multipleSelection);
      const h = this.$createElement;
      this.$msgbox({
        title: '提示',
        message: h('p', null, [
          h('span', null, '该操作'),
          h('b', { style: 'color: #0d2d84' }, '不可逆'),
          h('span', null, ', 是否确认 删除?')
        ]),
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(action => {
        this.axios({
          method: 'delete',
          url: '/api/batchoperation/',
          headers: {
            'Token': this.$cookies.get('__tk')
          },
          data: {
            pid_list: JSON.stringify(this.multipleSelection),
          }
        }).then(res => {
          // console.log('res==>', res)
          if (res.data.code == 200) {
            this.$message.success(res.data.msg)
            this.dialog.batch = false;
            this.search();
          } else {
            this.$message.error(res.data.msg)
          }
        }).catch(err => {
          // console.log('err==>', err)
          this.$message.error(res.data.msg)
        })
      });
    },
    // 转移科室
    changeKeshi() {
      if (!this.dialog.changeKs) {
        this.editData.department_id = '';
        this.editData.section_id = '';
        this.dialog.changeKs = true;
      } else {
        if (!this.editData.section_id) {
          return this.$message.warning('请选择科室')
        }
        // console.log("批量转移==>", this.multipleSelection);
        const h = this.$createElement;
        this.$msgbox({
          title: '提示',
          message: h('p', null, [
            h('span', null, '该操作'),
            h('b', { style: 'color: #0d2d84' }, '不可逆'),
            h('span', null, ', 是否确认 转移?')
          ]),
          showCancelButton: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(action => {
          this.axios({
            method: 'post',
            url: '/api/batchoperation/',
            headers: {
              'Token': this.$cookies.get('__tk')
            },
            data: this.$qs.stringify({
              pid_list: JSON.stringify(this.multipleSelection),
              section_id: this.editData.section_id
            })
          }).then(res => {
            // console.log('res==>', res)
            if (res.data.code == 200) {
              this.$message.success(res.data.msg)
              this.dialog.changeKs = false;
              this.dialog.batch = false;
              this.search();
            } else {
              this.$message.error(res.data.msg)
            }
          }).catch(err => {
            // console.log('err==>', err)
            this.$message.error(res.data.msg)
          })
        });
      }
    },
    // 当前页
    handleCurrentChange(p) {
      this.params.page = p;
      this.search()
    },
    // 多选
    handleSelectionChange(val) {
      this.multipleSelection = [];
      for (let i = 0; i < val.length; i++) {
        this.multipleSelection.push(val[i].id)
      }
    },
    // 条/页
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.params.pageSize = val;
      this.params.page = 1;
      this.search();
    },
    // 修改密码
    changePw() {
      if (this.$refs.pw_form) {
        this.$refs.pw_form.resetFields();
      }
      this.pw_form.n_pw = '';
      this.dialog.pw = true;
    },
    changePw2() {
      this.$refs['pw_form'].validate(valid => {
        if (valid) {
          this.axios({
            method: 'post',
            url: '/api/managerpwd/',
            headers: {
              'Token': this.$cookies.get('__tk')
            },
            data: this.$qs.stringify({ username: this.editData.mobile, pwd: this.pw_form.n_pw })
          }).then(res => {
            // console.log('res==>', res)
            if (res.data.code == 200) {
              this.$message.success(res.data.msg)
              this.dialog.pw = false;
            } else {
              this.$message.error(res.data.msg)
            }
          }).catch(error => {
            // console.log('error==>', error)
            this.$message.error(error || "出现错误，请稍后再试")
          });
        } else {
          this.$message.warning("请检查密码是否有误!");
          return false;
        }
      })
    },
    // 打开选择对话框
    openSelect() {
      this.selection = [];
      if (this.editData.authcode == 401 || this.editData.authcode == 101) {
        this.editData.auth_list = this.selection;
        this.editData.authcode2 = this.editData.authcode;
        return
      } else if (this.editData.authcode == 301 && !this.options.section2.length) {
        this.$message.warning('请先分配部门')
        this.editData.authcode = 401
        return
      }
      this.dialog.select = true;
    },
    openSelect2() {
      this.selection = [];
      this.editData.auth_list.forEach(e => {
        this.selection.push(e)
      });
      this.dialog.select = true;
    },
    // 添加/移除选中元素
    selectDmks(item) {
      if (this.$cookies.get('__un') == this.editData.mobile) {
        return
      }
      for (let i = 0; i < this.selection.length; i++) {
        if (this.selection[i] == item) {
          this.selection.splice(i, 1);
          // console.log('selection==>', this.selection)
          // console.log('auch_list==>', this.editData.auth_list)
          return
        }
      }
      this.selection.push(item);
      // console.log('auch_list==>', this.editData.auth_list)
      // console.log('selection==>', this.selection)
    },
    // 判断是否选中
    Selected(item) {
      for (let i = 0; i < this.selection.length; i++) {
        if (this.selection[i] == item) {
          return true;
        }
      }
      return false;
    },
    // 判断是否选择
    saveSelection() {
      if (!this.selection.length) {
        if (this.editData.authcode == 301) {
          this.$message.warning('请分配管理的科室')
        } else if (this.editData.authcode == 201) {
          this.$message.warning('请分配管理的部门')
        }
        return
      }
      // console.log('saveSelection')
      const h = this.$createElement;
      this.$msgbox({
        title: '提示',
        message: h('p', null, [
          h('span', null, '管理权限发生变化，是否确定'),
          h('b', { style: 'color: #0d2d84' }, '保存更改'),
          h('span', null, '？')
        ]),
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.editData.auth_list = this.selection;
        this.editData.authcode2 = this.editData.authcode;
        this.dialog.select = false;
        this.selection = [];
      }).catch(() => {
        return
      });
    },
    // 取消修改权限
    cancelSelection() {
      this.editData.authcode = this.editData.authcode2;
      this.dialog.select = false;
      this.selection = [];
    },
    // 输入框的输入建议
    querySearch(queryString, cb) {
      var seat_list = this.seat_list;
      var results = queryString ? seat_list.filter(this.createFilter(queryString)) : seat_list;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (state) => {
        return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    // 获取所有空座
    loadAll() {
      this.axios({
        method: 'get',
        url: '/api/seatsoperations/',
        headers: {
          'Token': this.$cookies.get('__tk')
        },
        params: {
          hasman: '0',
          // searchText: this.params.searchText,
          username: this.$cookies.get('__un')
        }
      }).then(res => {
        // console.log('res==>', res)
        if (res.data.code == 200) {
          res.data.data.forEach(e => {
            let o = { "value": '' };
            o["value"] = e.seatid;
            this.seat_list.push(o);
          });
          // console.log('this.seat_list==>', this.seat_list)
        }
      }).catch(err => {
        // console.log('err==>', err)
        this.$message.error(err || "出现错误，请稍后再试")
      })
      // return arr;
    },
    // 修改座位id
    handleSelect(item) {
      // console.log(item);
      this.editData.seatinfo.seatid = item.value;
      this.validSeatid;
    },
    // ----------------------------------------------验证---------------------------------------------------
    // 验证姓名
    validName(rule, value, callback) {
      if (value == "") {
        // callback();
        callback(new Error("请输入姓名"));
      } else if (!/^[\u4e00-\u9fa5·]{2,5}|[a-zA-Z]$/.test(value)) {
        callback(new Error("姓名有误!"));
      } else {
        callback();
      }
    },
    // 验证手机号
    validMobile(rule, value, callback) {
      if (value == "") {
        // callback();
        callback(new Error("请输入手机号"));
      } else if (!/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(value)) {
        callback(new Error("手机格式错误!"));
      } else {
        callback();
      }
    },
    // 验证部门
    validDepartment(rule, value, callback) {
      if (value == "") {
        callback(new Error("请选择部门!"));
      } else {
        callback();
      }
    },
    // 验证科室
    validSectionId(rule, value, callback) {
      if (value == "") {
        callback(new Error("请选择科室!"));
      } else {
        callback();
      }
    },
    // 验证职务
    validPosition(rule, value, callback) {
      if (value == "" || value == null) {
        callback();
      } else {
        callback();
      }
    },
    // 验证邮箱
    validEmail(rule, value, callback) {
      if (value == "" || value == '暂无') {
        callback();
      } else {
        if (!/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(value)) {
          callback(new Error("邮箱格式错误!"));
        } else {
          callback();
        }
      }
    },
    // 验证房间号
    validRoomnumber(rule, value, callback) {
      if (value != "") {
        let reg = /^([\d]{3,})|([\d]{3,}[a-zA-Z]{1})$/;
        if (!reg.test(value)) {
          callback(new Error("请输入正确的房间号"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    },
    // 验证卡位编号
    validSeatid(rule, value, callback) {
      setTimeout(() => {
        if (value != "") {
          if (this.editData.seatinfo.seatid == this.editData.seatinfo.seatid2) {
            callback()
            return;
          }
          this.axios({
            method: 'get',
            url: '/api/checkseatid/',
            headers: {
              'Token': this.$cookies.get('__tk')
            },
            params: { seatid: this.editData.seatinfo.seatid }
          }).then(res => {
            // console.log('seatid res==>', res)
            if (res.data.code == 200) {
              // 可分配
              this.editData.seatinfo.id = res.data.data.data.id;
              // console.log('id==>', res.data.data.data.id)
              // this.editData.seatinfo.ipaddress = res.data.data.ipaddress;
              // this.editData.seatinfo.roomnumber = res.data.data.roomnumber;
              // this.editData.seatinfo.roomname = res.data.data.roomname;
              // this.editData.seatinfo.phonenumber = res.data.data.phonenumber;
              callback()
            } else if (res.data.code == 400) {
              // 无座/有人
              callback(new Error(res.data.msg))
            }
            callback();
          }).catch(error => {
            // console.log('error==>', error)
            callback()
          })
        } else {
          callback(new Error('卡位编号不能为空'));
        }
      }, 400)
    },
    // 验证内线
    validPhonenumber(rule, value, callback) {
      if (value != "") {
        let reg = /^[0-9\-]{5,}$/;
        if (!reg.test(value)) {
          callback(new Error("请输入正确的内线"));
        } else {
          callback();
        }
      } else {
        callback();
      }
    },
    // 验证IP地址
    validIpaddress(rule, value, callback) {
      if (value == "" || value == '暂无') {
        // callback(new Error("请输入IP地址"));
        callback();
      } else {
        let reg = /^([1-9]\d?|1\d{2}|2[0-4]\d|25[0-5])(\.([1-9]?\d|1\d{2}|2[0-4]\d|25[0-5])){3}$/;
        if (!reg.test(value)) {
          callback(new Error("IP地址有误!"));
        }
        callback();
      }
    },
    validN_pw(rule, value, callback) {
      if (value === "") {
        callback();
      } else {
        callback();
      }
    },


    // 上传之前
    beforeUpload(file) {
      // console.log(file, '文件');
      const extension = file.name.split(".")[1] == "xls";
      const extension2 = file.name.split(".")[1] === "xlsx";
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!extension && !extension2) {
        this.$message.warning("上传模板只能是 xls、xlsx格式!");
        return;
      }
      if (!isLt5M) {
        this.$message.warning("上传模板大小不能超过 5MB!");
        return;
      }
      // console.log("上传文件==>" + file.name);
      if (this.fileName == "") {
        this.$message.warning("请选择要上传的文件！");
        return false;
      }
      this.loading2 = true;
    },
    // 上传成功
    onSuccess(response, file, fileList) {
      // console.log('response==>', response)
      // console.log('file==>', file)
      fileList = [];
      this.loading2 = false;
      if (response.msg) {
        this.$message.success(response.msg)
      } else {
        this.$message.success('数据库更新成功')
      }
      this.search();
    },
    // 上传失败
    onError(err, file, fileList) {
      // console.log('err==>', err)
      // console.log('file==>', file)
      fileList = [];
      this.loading2 = false;
      this.$message.error('上传失败，请重新检查文档')
      this.search();
    },
    // 下载文件
    download() {
      this.axios({
        method: 'post',
        url: '/api/getexcel/',
        headers: {
          'Token': this.$cookies.get('__tk')
        },
        data: this.$qs.stringify({
          username: this.$cookies.get('__un'),
          authcode: this.$cookies.get('__ac')
        }),
        responseType: 'blob',
      }).then(res => {
        // console.log('res==>', res)
        const fileName = decodeURI( // 获取文件名
          res.headers['content-disposition'].split('=')[1].replace("utf-8''", '')
        )

        // Blob 对象表示一个不可变、原始数据的类文件对象（File 接口都是基于Blob）
        const BLOB = res.data
        // FileReader 对象允许Web应用程序异步读取存储在用户计算机上的文件的内容
        const fileReader = new FileReader()
        // 开始读取指定的Blob中的内容。读取完成result属性中将包含一个data: URL格式的Base64字符串以表示所读取文件的内容

        if (BLOB) { // 此处判断是否有数据，也可以在此判断文件类型是否符合
          fileReader.readAsDataURL(BLOB)
        }

        // 处理load事件，该事件在读取操作完成时触发
        fileReader.onload = (event) => {
          let a = document.createElement('a')
          // a.download = `${name}.xls` // 自定义文件名
          a.download = fileName // 使用默认的文件名
          a.href = event.target.result
          document.body.appendChild(a)
          a.click()
          document.body.removeChild(a)
        }
      }).catch(err => {
        // console.log('err==>', err)
      })
    },
  }
};
</script>

<style lang="scss" scoped>
.admin {
  .container {
    padding: 20px;
    background-color: #fff;
    border-radius: 6px;
    height: calc(100% - 40px);
    .top {
      padding-bottom: 10px;
      margin-bottom: 10px;
      border-bottom: 1px solid #ccc;
      >>> .el-breadcrumb {
        font-size: 20px;
        height: 40px;
        line-height: 40px;
      }
    }
    .header-op {
      height: 62px;
      .el-select,
      .el-input {
        max-width: 200px;
      }
    }
    >>> .el-table {
      margin-bottom: 10px;
    }
    >>> .el-pagination {
      text-align: center;
    }
    >>> .el-dialog {
      max-width: 1100px;
      .title {
        font-size: 20px;
        height: 20px;
        line-height: 1;
        text-align: center;
        font-weight: bold;
        color: #000;
      }

      .el-form-item__content {
        position: relative;
        .el-tooltip {
          position: absolute;
          right: -25px;
          transform: translateY(50%);
        }
      }

      .btns {
        text-align: center;
        .el-button {
          width: 200px;
          height: 40px;

          & + .el-button {
            margin-left: 60px;
          }
        }
      }
    }
    .dialog-select {
      >>> .el-dialog__body {
        padding-top: 10px;
        .total {
          text-align: right;
        }
        .selection {
          max-height: 350px;
          overflow: hidden;
          overflow-y: auto;
          margin-bottom: 10px;
          &::-webkit-scrollbar {
            display: none;
          }

          ul {
            > li {
              height: 30px;
              line-height: 30px;
              // text-align: center;
              cursor: pointer;

              .icon-span {
                display: inline-block;
                background-color: #fff;
                border-radius: 4px;
                border: 2px solid #7f7f7f;
                position: relative;
                width: 18px;
                height: 18px;
                vertical-align: middle;
              }
              .icon-span::after {
                border: 2px solid transparent;
                border-left: 0;
                border-top: 0;
                content: " ";
                top: 2px;
                left: 5px;
                position: absolute;
                width: 4px;
                height: 8px;
                transform: rotate(45deg) scale(0);
                transition: transform 0.2s;
              }
              .icon-span-select {
                background-color: #0d2d84;
              }
              .icon-span-select::after {
                border-color: #fff;
                transform: rotate(45deg) scale(1);
              }
            }
          }
        }
        .btns {
          .el-button {
            width: 100px;
          }
        }
      }
    }
  }
}
</style>